import express, { Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from 'uuid';
import { query } from '../database';
import { body, validationResult } from 'express-validator';
import CryptoJS from 'crypto-js';

const router = express.Router();
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// 用户注册
router.post('/register', [
  body('username').isLength({ min: 3, max: 50 }).withMessage('用户名长度必须在3-50字符之间'),
  body('password').isLength({ min: 6 }).withMessage('密码长度至少6位'),
  body('role').optional().isIn(['admin', 'user']).withMessage('角色只能是admin或user')
], async (req: Request, res: Response) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        success: false, 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    const { username, password, role = 'user' } = req.body;

    // 检查用户名是否已存在
    const existingUser = await query('SELECT id FROM users WHERE username = ?', [username]);
    if ((existingUser as any[]).length > 0) {
      return res.status(400).json({ 
        success: false, 
        message: '用户名已存在' 
      });
    }

    // 创建新用户 - 对客户端发送的密码进行MD5加密
    const userId = uuidv4();
    const hashedPassword = CryptoJS.MD5(password).toString();

    await query(
      'INSERT INTO users (id, username, password, role) VALUES (?, ?, ?, ?)',
      [userId, username, hashedPassword, role]
    );

    res.status(201).json({
      success: true,
      message: '用户注册成功',
      data: { id: userId, username, role }
    });

  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 用户登录
router.post('/login', [
  body('username').notEmpty().withMessage('用户名不能为空'),
  body('password').notEmpty().withMessage('密码不能为空')
], async (req: Request, res: Response) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        success: false, 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    const { username, password } = req.body;

    // 查找用户
    const users = await query('SELECT * FROM users WHERE username = ?', [username]);
    const user = (users as any[])[0];
    if (!user) {
      return res.status(401).json({ 
        success: false, 
        message: '用户名或密码错误' 
      });
    }

    // 验证密码 - 对客户端发送的密码进行MD5加密后与数据库中的密码比较
    const hashedInputPassword = password;
    const isValidPassword = hashedInputPassword === user.password;
    if (!isValidPassword) {
      return res.status(401).json({ 
        success: false, 
        message: '用户名或密码错误' 
      });
    }

    // 生成JWT token
    const token = jwt.sign(
      { 
        userId: user.id, 
        username: user.username, 
        role: user.role 
      },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          role: user.role
        }
      }
    });

  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

// 修改密码
router.put('/change-password', [
  body('oldPassword').notEmpty().withMessage('原密码不能为空'),
  body('newPassword').isLength({ min: 6 }).withMessage('新密码长度至少6位')
], async (req: Request, res: Response) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    if (!token) {
      return res.status(401).json({ 
        success: false, 
        message: '未提供认证token' 
      });
    }

    const decoded = jwt.verify(token, JWT_SECRET) as any;
    const { oldPassword, newPassword } = req.body;

    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        success: false, 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    // 获取用户信息
    const users = await query('SELECT * FROM users WHERE id = ?', [decoded.userId]);
    const user = (users as any[])[0];

    if (!user) {
      return res.status(404).json({ 
        success: false, 
        message: '用户不存在' 
      });
    }

    // 验证原密码 - 客户端已经发送了加密后的密码
    const isValidOldPassword = oldPassword === user.password;
    if (!isValidOldPassword) {
      return res.status(400).json({ 
        success: false, 
        message: '原密码错误' 
      });
    }

    // 更新密码 - 客户端已经发送了加密后的密码
    await query('UPDATE users SET password = ? WHERE id = ?', [newPassword, decoded.userId]);

    res.json({
      success: true,
      message: '密码修改成功'
    });

  } catch (error) {
    console.error('修改密码失败:', error);
    res.status(500).json({ 
      success: false, 
      message: '服务器内部错误' 
    });
  }
});

export default router;
